package emulator.shell.GUI.menu;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import emulator.cbm.basic.BasicHelper;
import emulator.shell.DebugShell;
import emulator.shell.GUI.ConsoleFrame;
import emulator.util.file.FileHelper;
import emulator.util.file.FileInfo;
import emulator.util.file.FileSaveStrategy;

public class FileSave implements ActionListener {

	private ConsoleFrame console;
	
	public FileSave(ConsoleFrame consoleFrame) {
		console = consoleFrame;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		MemoryFileDialog dlg = new MemoryFileDialog(console.getFrame(), "Save", true);
		int basic_start = BasicHelper.getBasicStart();
		int basic_end = BasicHelper.getBasicEnd();
		if (basic_start > 0 && basic_end > basic_start)
		{
			dlg.setStartAddress(basic_start);
			dlg.setBlockSize(basic_end - basic_start);
		}
		dlg.setVisible(true);
		if (dlg.isResultValid())
		{
			FileInfo info = FileHelper.getFileInfo(dlg.getFileName(), dlg.getFileFormat());
			FileSaveStrategy save_strategy = (info != null ? info.getSaveStrategy() : null);
			if (save_strategy != null)
			{
				save_strategy.saveFromMemory(dlg.getFileName(),
													DebugShell.getInstance().getMemoryBlock(),
													dlg.getStartAddress(),
													dlg.getBlockSize());
			}
			else
				JOptionPane.showMessageDialog(null, "File format not supported yet.");
		}
	}

}
